package com.rla.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.rla.common.constant.RegisterConstants;
import com.rla.common.core.page.TableDataInfo;
import com.rla.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.rla.common.exception.ServiceException;
import com.rla.common.utils.SecurityUtils;
import com.rla.common.utils.StringUtils;
import com.rla.common.wechat.utils.RestTemplateUtil;
import com.rla.domain.*;
import com.rla.domain.vo.BaseHealthTargetRuleVo;
import com.rla.domain.vo.BloodGlucoseSnVo;
import com.rla.mapper.*;
import com.rla.service.IBaseHealthTargetRuleService;
import com.rla.service.IIntegralTaskService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.rla.domain.bo.EhsEverydayBloodGlucoseBo;
import com.rla.domain.vo.EhsEverydayBloodGlucoseVo;
import com.rla.service.IEhsEverydayBloodGlucoseService;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

/**
 * 日常记录-血糖记录Service业务层处理
 *
 * @author rla
 * @date 2025-07-30
 */
@RequiredArgsConstructor
@Service
public class EhsEverydayBloodGlucoseServiceImpl implements IEhsEverydayBloodGlucoseService {

    private final EhsEverydayBloodGlucoseMapper baseMapper;

    private final EhsEverydayWeightMapper weightMapper;
    private final EhsEverydayUricAcidMapper uricAcidMapper;
    private final EhsEverydayBloodFatMapper fatMapper;
    private final EhsEverydayBloodPressureMapper bloodPressureMapper;
    private final RestTemplateUtil restTemplateUtil;


    private final IBaseHealthTargetRuleService iBaseHealthTargetRuleService;
    private final VipUserInfoMapper vipUserInfoMapper;

    private final IIntegralTaskService iIntegralTaskService;

    /**
     * 查询日常记录-血糖记录
     */
    @Override
    public EhsEverydayBloodGlucoseVo queryById(String id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询日常记录-血糖记录列表
     */
    @Override
    public TableDataInfo<EhsEverydayBloodGlucoseVo> queryPageList(EhsEverydayBloodGlucoseBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<EhsEverydayBloodGlucose> lqw = buildQueryWrapper(bo);
        Page<EhsEverydayBloodGlucoseVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    @Override
    public List<Map<String,Object>> appListByTime(EhsEverydayBloodGlucoseBo bo, PageQuery pageQuery) {
        List<Map<String,Object>> list = ListUtils.newArrayList();

        bo.setUserId(SecurityUtils.getUserId().toString());
        List<Map<String, Object>> maps = baseMapper.queryTimeGroup(bo.getUserId());

        for (Map<String, Object> map : maps) {
            Map<String,Object> map1 = MapUtil.newHashMap();
            bo.setMeasuredTime(map.get("year").toString()+"-"+map.get("month").toString());
            LambdaQueryWrapper<EhsEverydayBloodGlucose> lqw = buildQueryWrapper(bo);
            List<EhsEverydayBloodGlucoseVo> ehsEverydayBloodGlucoseVos = baseMapper.selectVoList(lqw);
            map1.put("time",map.get("year").toString()+"-"+map.get("month").toString());
            map1.put("list",ehsEverydayBloodGlucoseVos);
            list.add(map1);
        }

        return list;
    }

    /**
     * 查询日常记录-血糖记录列表
     */
    @Override
    public List<EhsEverydayBloodGlucoseVo> queryList(EhsEverydayBloodGlucoseBo bo) {
        LambdaQueryWrapper<EhsEverydayBloodGlucose> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<EhsEverydayBloodGlucose> buildQueryWrapper(EhsEverydayBloodGlucoseBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<EhsEverydayBloodGlucose> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getUserId()), EhsEverydayBloodGlucose::getUserId, bo.getUserId());
        lqw.like(StringUtils.isNotBlank(bo.getMeasuredTime()), EhsEverydayBloodGlucose::getMeasuredTime, bo.getMeasuredTime());
        lqw.eq(StringUtils.isNotBlank(bo.getMeasuredType()), EhsEverydayBloodGlucose::getMeasuredType, bo.getMeasuredType());
        lqw.eq(StringUtils.isNotBlank(bo.getBloodGlucose()), EhsEverydayBloodGlucose::getBloodGlucose, bo.getBloodGlucose());
        lqw.eq(StringUtils.isNotBlank(bo.getSourceType()), EhsEverydayBloodGlucose::getSourceType, bo.getSourceType());
        lqw.like(StringUtils.isNotBlank(bo.getSourceName()), EhsEverydayBloodGlucose::getSourceName, bo.getSourceName());
        lqw.eq(StringUtils.isNotBlank(bo.getIsLook()), EhsEverydayBloodGlucose::getIsLook, bo.getIsLook());
        lqw.like(StringUtils.isNotBlank(bo.getTag()), EhsEverydayBloodGlucose::getTag, bo.getTag());
        lqw.eq(StringUtils.isNotBlank(bo.getBusinessId()), EhsEverydayBloodGlucose::getBusinessId, bo.getBusinessId());
        lqw.orderByDesc(EhsEverydayBloodGlucose::getMeasuredTime);
        return lqw;
    }

    /**
     * 新增日常记录-血糖记录
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String insertByBo(EhsEverydayBloodGlucoseBo bo) {
        bo.setUserId(SecurityUtils.getUserId().toString());
        EhsEverydayBloodGlucose add = BeanUtil.toBean(bo, EhsEverydayBloodGlucose.class);
        validEntityBeforeSave(add);
        add.setCreateBy(SecurityUtils.getUserId().toString());
        add.setCreateTime(new Date());
        Map<String, Object> resultMap = iBaseHealthTargetRuleService.calculateIndicators("血糖", bo.getMeasuredType(), Double.valueOf(bo.getBloodGlucose()));
        if(ObjectUtil.isNotEmpty(resultMap)){
            add.setTag(resultMap.get("tag").toString());
            add.setColor(resultMap.get("color").toString());
        }
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }

        //异步完成积分任务
        iIntegralTaskService.pointsRule("15",SecurityUtils.getUserId().toString());

        return add.getId();
    }

    /**
     * 修改日常记录-血糖记录
     */
    @Override
    public Boolean updateByBo(EhsEverydayBloodGlucoseBo bo) {
        EhsEverydayBloodGlucose update = BeanUtil.toBean(bo, EhsEverydayBloodGlucose.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(EhsEverydayBloodGlucose entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除日常记录-血糖记录
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<String> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public List<Map<String, Object>> queryTrendList(EhsEverydayBloodGlucoseBo bo) {

        List<Map<String, Object>> list = new ArrayList<>();
//        DateUtil
        String startDate = bo.getStartDate()+" 00:00:00";
        String endDate = bo.getEndDate()+" 23:59:59";

        String queryFlag = bo.getQueryFlag();
        //趋势数据图表
        list = baseMapper.getTrendList(bo.getUserId(),startDate,endDate);

        // 根据queryFlag处理数据
        if ("day".equals(queryFlag)) {
            // 日查询：按小时分组计算平均值
            list = processHourlyAverage(list);
        } else {
            // 其他查询：按天分组计算平均值
            list = processDailyAverage(list);
        }

        return list;
    }

    @Override
    public Map<String, Object> statisticsExce(EhsEverydayBloodGlucoseBo bo) {
        //正常异常数量统计
        String startDate = bo.getStartDate()+" 00:00:00";
        String endDate = bo.getEndDate()+" 23:59:59";
        List<Map<String, Object>> maps = baseMapper.statisticsExce(bo.getUserId(), startDate, endDate);
        Map<String, Object> map1 = new HashMap<>();
        if(ObjectUtil.isNotEmpty(maps)){
            for (Map<String, Object> map : maps) {
                map1.put(map.get("tag").toString(), map.get("num").toString());
            }
        }
        return map1;
    }

    @Override
    public List<Map<String, Object>> queryTypeList(String targetId) {
        return baseMapper.queryTypeList(targetId);
    }

    @Override
    public Map<String, Object> queryDateCompare(String id) {

        Map<String, Object> map1 = new HashMap<>();

        EhsEverydayBloodGlucoseVo vo = baseMapper.selectVoById(id);
        String measuredTime = vo.getMeasuredTime();
        String bloodGlucose = vo.getBloodGlucose();
        Map<String, Object> map = baseMapper.queryDateCompare(measuredTime);

        //最近一次
        if(ObjectUtil.isNotEmpty(map)){
            String bloodGlucoseNext = map.get("bloodGlucose").toString();
            BigDecimal subtract = new BigDecimal(bloodGlucose).subtract(new BigDecimal(bloodGlucoseNext));
            map1.put("lastDiff", subtract);
            map1.put("lastDate", map.get("measuredTimeFormat").toString());
            if (subtract.compareTo(BigDecimal.ZERO) > 0){
                map1.put("lastFlag", "1");
            }else {
                map1.put("lastFlag", "0");
            }
        }else {
            map1.put("lastFlag", "0");
            map1.put("lastDiff", "-");
            map1.put("lastDate", "-");
        }

        //近10天
        DateTime parse = DateUtil.parse(measuredTime);
        String dateStr = DateUtil.offsetDay(parse, -10).toDateStr();
        Map<String, Object> mapTen = baseMapper.queryDateCompare(dateStr);
        if (ObjectUtil.isNotEmpty(mapTen)){
            String bloodGlucoseTen = mapTen.get("bloodGlucose").toString();
            BigDecimal subtract = new BigDecimal(bloodGlucose).subtract(new BigDecimal(bloodGlucoseTen));
            map1.put("tenDaysDiff", subtract);
            map1.put("tenDaysDate", mapTen.get("measuredTimeFormat").toString());
            String dateStr1 = measuredTime;
            Date date1 = DateUtil.parse(dateStr1);

            String dateStr2 = mapTen.get("measuredTime").toString();
            Date date2 = DateUtil.parse(dateStr2);

            long betweenDay = DateUtil.between(date1, date2, DateUnit.DAY);
            map1.put("betweenDay", betweenDay);

            if (subtract.compareTo(BigDecimal.ZERO) > 0){
                map1.put("tenDaysFlag", "1");
            }else {
                map1.put("tenDaysFlag", "0");
            }
        }else {
            map1.put("tenDaysFlag", "0");
            map1.put("tenDaysDiff", "-");
            map1.put("tenDaysDate", "-");
            map1.put("betweenDay", "-");
        }


        return map1;
    }

    @Override
    public Map<String, Object> getHealthDataNext() {
        Map<String, Object> map = new HashMap<>();
        LambdaQueryWrapper<EhsEverydayBloodGlucose> lqw = Wrappers.lambdaQuery(EhsEverydayBloodGlucose.class)
                .eq(EhsEverydayBloodGlucose::getUserId,SecurityUtils.getUserId())
                .orderByDesc(EhsEverydayBloodGlucose::getMeasuredTime);
        List<EhsEverydayBloodGlucose> bloodGlucoseList = baseMapper.selectList(lqw);
        if(ObjectUtil.isNotEmpty(bloodGlucoseList)){
            map.put("bloodGlucose", bloodGlucoseList.get(0).getBloodGlucose());
            map.put("bloodGlucoseTime", bloodGlucoseList.get(0).getMeasuredTime());
        }

        LambdaQueryWrapper<EhsEverydayWeight> lqw1 = Wrappers.lambdaQuery(EhsEverydayWeight.class)
                .eq(EhsEverydayWeight::getUserId,SecurityUtils.getUserId())
                .orderByDesc(EhsEverydayWeight::getMeasuredTime);
        List<EhsEverydayWeight> weightList = weightMapper.selectList(lqw1);
        if(ObjectUtil.isNotEmpty(weightList)){
            map.put("weight", weightList.get(0).getWeight());
            map.put("weightTime", weightList.get(0).getMeasuredTime());
        }

        LambdaQueryWrapper<EhsEverydayBloodFat> lqw2 = Wrappers.lambdaQuery(EhsEverydayBloodFat.class)
                .eq(EhsEverydayBloodFat::getUserId,SecurityUtils.getUserId())
                .orderByDesc(EhsEverydayBloodFat::getMeasuredTime);
        List<EhsEverydayBloodFat> bloodFatList = fatMapper.selectList(lqw2);
        if (ObjectUtil.isNotEmpty(bloodFatList)){
            map.put("bloodFat",bloodFatList.get(0).getTc());
            map.put("bloodFatTime",bloodFatList.get(0).getMeasuredTime());
        }

        LambdaQueryWrapper<EhsEverydayUricAcid> lqw3 = Wrappers.lambdaQuery(EhsEverydayUricAcid.class)
                .eq(EhsEverydayUricAcid::getUserId,SecurityUtils.getUserId())
                .orderByDesc(EhsEverydayUricAcid::getMeasuredTime);
        List<EhsEverydayUricAcid> uricAcidList = uricAcidMapper.selectList(lqw3);
        if(ObjectUtil.isNotEmpty(uricAcidList)){
            map.put("uricAcid",uricAcidList.get(0).getUricAcid());
            map.put("uricAcidTime",uricAcidList.get(0).getMeasuredTime());
        }

        LambdaQueryWrapper<EhsEverydayBloodPressure> lqw4 = Wrappers.lambdaQuery(EhsEverydayBloodPressure.class)
                .eq(EhsEverydayBloodPressure::getUserId,SecurityUtils.getUserId())
                .orderByDesc(EhsEverydayBloodPressure::getMeasuredTime);
        List<EhsEverydayBloodPressure> bloodPressureList = bloodPressureMapper.selectList(lqw4);
        if(ObjectUtil.isNotEmpty(bloodPressureList)){
            map.put("bloodPressure",bloodPressureList.get(0).getSystolicPressure()+"/"+bloodPressureList.get(0).getDiastolicPressure());
            map.put("bloodPressureTime",bloodPressureList.get(0).getMeasuredTime());
        }
        return map;
    }

    @Override
    public Map<String, Object> healthReport(EhsEverydayBloodGlucoseBo bo) {
        String startDate = bo.getStartDate()+" 00:00:00";
        String endDate = bo.getEndDate()+" 23:59:59";
        Map<String, Object> healthReportCountMap = baseMapper.healthReport(bo.getUserId(), startDate, endDate);
        Map<String, Object> map1 = new HashMap<>();

        List<Map<String, Object>> maps = baseMapper.getTagCountStatistics(bo.getUserId(), startDate, endDate);
        if(ObjectUtil.isNotEmpty(maps)){
            for (Map<String, Object> map : maps) {
                map1.put(map.get("tagName").toString(), map.get("tagCount").toString());
            }
        }
        map1.put("count",ObjectUtil.isNotEmpty(healthReportCountMap.get("num"))? healthReportCountMap.get("num"):0 );
        map1.put("minValue",ObjectUtil.isNotEmpty(healthReportCountMap.get("min_value"))? healthReportCountMap.get("min_value"):0 );
        map1.put("maxValue",ObjectUtil.isNotEmpty(healthReportCountMap.get("max_value"))? healthReportCountMap.get("max_value"):0 );
        map1.put("avgValue",ObjectUtil.isNotEmpty(healthReportCountMap.get("avg_value"))? healthReportCountMap.get("avg_value"):0 );
        return map1;


    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean pushBloodGlucoseDataFromDP(EhsEverydayBloodGlucoseBo bo) {
                if(ObjectUtil.isEmpty(bo.getBloodGlucose())){
            throw new ServiceException("血糖值不能为空！");
        }
        if(ObjectUtil.isEmpty(bo.getMeasuredTime())){
            throw new ServiceException("测量时间不能为空！");
        }
//        if(ObjectUtil.isEmpty(bo.getVipCode())){
//            throw new ServiceException("会员编号不能为空！");
//        }

        EhsEverydayBloodGlucose add = BeanUtil.toBean(bo, EhsEverydayBloodGlucose.class);

        LambdaQueryWrapper<VipUserInfo> lqw1 = Wrappers.lambdaQuery(VipUserInfo.class)
                .eq(VipUserInfo::getSn, bo.getSn());
        List<VipUserInfo> vipUserInfos = vipUserInfoMapper.selectList(lqw1);
        if(ObjectUtil.isNotEmpty(vipUserInfos)){
            add.setUserId(vipUserInfos.get(0).getId());
        }else {
            throw new ServiceException("sn码为绑定不做处理！");
//            add.setUserId("pd");
        }

        LambdaQueryWrapper<EhsEverydayBloodGlucose> lqw = Wrappers.lambdaQuery(EhsEverydayBloodGlucose.class)
                .eq(EhsEverydayBloodGlucose::getIdl, bo.getIdl());
        List<EhsEverydayBloodGlucose> ehsEverydayBloodGlucoses = baseMapper.selectList(lqw);

        if (ObjectUtil.isEmpty(ehsEverydayBloodGlucoses)) {
            Map<String, Object> resultMap = iBaseHealthTargetRuleService.calculateIndicators("血糖", "12", Double.valueOf(bo.getBloodGlucose()));
            if(ObjectUtil.isNotEmpty(resultMap)){
                add.setTag(resultMap.get("tag").toString());
                add.setColor(resultMap.get("color").toString());
            }
            add.setMeasuredType("12");
            add.setSourceName("设备上传");
            baseMapper.insert(add);
        }else {
            throw new ServiceException("数据已存在无需重复添加！");
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean bindSn(EhsEverydayBloodGlucoseBo bo) {
        String sn = bo.getSn();
        if (StringUtils.isEmpty(sn)) {
            throw new ServiceException("请输入要绑定的sn码！");
        }

        UpdateWrapper<VipUserInfo> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", SecurityUtils.getUserId())
                .set("sn", sn);
        vipUserInfoMapper.update(null, updateWrapper);

        JSONObject bloodsugarBysn = getBloodsugarBysn(sn);
        if (ObjectUtil.isNotEmpty((bloodsugarBysn)) ){
            JSONArray gj = bloodsugarBysn.getJSONArray("GJ");
            List<BloodGlucoseSnVo> list = (ArrayList<BloodGlucoseSnVo>) gj.toJavaList(BloodGlucoseSnVo.class);
            if (ObjectUtil.isNotEmpty(list)) {

                //删除之前sn数据，插入新的
                LambdaQueryWrapper<EhsEverydayBloodGlucose> lqw = Wrappers.lambdaQuery();
                lqw.eq(EhsEverydayBloodGlucose::getSn, sn);
                baseMapper.delete(lqw);

                // 转换BloodGlucoseSnVo列表为EhsEverydayBloodGlucose列表
                List<EhsEverydayBloodGlucose> bloodGlucoseList = convertBloodGlucoseSnVoToEhsEverydayBloodGlucose(list, sn);
                
                // 批量插入新的血糖数据
                if (ObjectUtil.isNotEmpty(bloodGlucoseList)) {
                    for (EhsEverydayBloodGlucose bloodGlucose : bloodGlucoseList) {
                        bloodGlucose.setUserId(SecurityUtils.getUserId().toString());
                        baseMapper.insert(bloodGlucose);
                    }
                }
            }
        }

        return true;
    }

    public JSONObject getBloodsugarBysn(String sn){
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("sn", sn);
        String data = restTemplateUtil.postMapData(RegisterConstants.bloodsugar, map);
        JSONObject jsonObject = JSON.parseObject(data);
        return jsonObject;
    }

    /**
     * 转换BloodGlucoseSnVo列表为EhsEverydayBloodGlucose列表
     * @param bloodGlucoseSnVoList BloodGlucoseSnVo列表
     * @param sn 设备序列号
     * @return EhsEverydayBloodGlucose列表
     */
    private List<EhsEverydayBloodGlucose> convertBloodGlucoseSnVoToEhsEverydayBloodGlucose(List<BloodGlucoseSnVo> bloodGlucoseSnVoList, String sn) {
        List<EhsEverydayBloodGlucose> result = new ArrayList<>();
        
        for (BloodGlucoseSnVo vo : bloodGlucoseSnVoList) {
            EhsEverydayBloodGlucose bloodGlucose = new EhsEverydayBloodGlucose();
            
            // 字段映射
            bloodGlucose.setBloodGlucose(vo.getV());        // v -> bloodGlucose
            bloodGlucose.setMeasuredTime(vo.getTime());     // time -> measuredTime
            bloodGlucose.setSn(vo.getSn());                 // sn -> sn
            bloodGlucose.setIdl(vo.getID());                // ID -> idl
            
            // 设置其他必要字段
            bloodGlucose.setUserId(SecurityUtils.getUserId().toString());
            bloodGlucose.setMeasuredType("12"); // 默认类型
            bloodGlucose.setSourceType("2");    // 移动设备
            bloodGlucose.setSourceName("设备上传");
            bloodGlucose.setIsLook("0");        // 未查看
            bloodGlucose.setDelFlag("0");       // 未删除
            bloodGlucose.setCreateBy(SecurityUtils.getUserId().toString());
            bloodGlucose.setCreateTime(new Date());
            
            // 计算健康指标标签和颜色
            if (StringUtils.isNotBlank(vo.getV())) {
                try {
                    Map<String, Object> resultMap = iBaseHealthTargetRuleService.calculateIndicators("血糖", "12", Double.valueOf(vo.getV()));
                    if (ObjectUtil.isNotEmpty(resultMap)) {
                        bloodGlucose.setTag(resultMap.get("tag").toString());
                        bloodGlucose.setColor(resultMap.get("color").toString());
                    }
                } catch (Exception e) {
                    // 如果计算失败，使用默认值
                    bloodGlucose.setTag("正常");
                    bloodGlucose.setColor("green");
                }
            }
            
            result.add(bloodGlucose);
        }
        
        return result;
    }

    /**
     * 按小时分组计算平均值（用于日查询）
     * @param originalList 原始数据列表
     * @return 按小时平均后的数据列表
     */
    private List<Map<String, Object>> processHourlyAverage(List<Map<String, Object>> originalList) {
        if (ObjectUtil.isEmpty(originalList)) {
            return originalList;
        }

        // 使用Map来存储每个小时的数据，key为小时，value为该小时的所有血糖值
        Map<Integer, List<Double>> hourlyData = new HashMap<>();
        Map<Integer, String> hourlyColor = new HashMap<>();

        for (Map<String, Object> item : originalList) {
            String measuredTime = item.get("measuredTime").toString();
            String bloodGlucoseStr = item.get("bloodGlucose").toString();
            String color = item.get("color") != null ? item.get("color").toString() : "green";

            try {
                // 解析日期时间，提取小时
                DateTime dateTime = DateUtil.parse(measuredTime);
                int hour = dateTime.hour(true); // 获取小时数 (0-23)

                double bloodGlucose = Double.parseDouble(bloodGlucoseStr);

                // 按小时分组
                hourlyData.computeIfAbsent(hour, k -> new ArrayList<>()).add(bloodGlucose);
                hourlyColor.put(hour, color); // 保存颜色信息

            } catch (Exception e) {
                // 如果解析失败，跳过这条数据
                continue;
            }
        }

        // 计算每个小时的平均值
        List<Map<String, Object>> result = new ArrayList<>();
        for (Map.Entry<Integer, List<Double>> entry : hourlyData.entrySet()) {
            int hour = entry.getKey();
            List<Double> values = entry.getValue();

            // 计算平均值
            double average = values.stream().mapToDouble(Double::doubleValue).average().orElse(0.0);

            Map<String, Object> resultItem = new HashMap<>();
            resultItem.put("measuredTime", String.format("%02d:00", hour)); // 横坐标返回格式化的小时，如00:00, 01:00
            resultItem.put("bloodGlucose", String.format("%.1f", average));
            resultItem.put("color", hourlyColor.get(hour));

            result.add(resultItem);
        }

        // 按小时排序
        result.sort((a, b) -> {
            String timeA = (String) a.get("measuredTime");
            String timeB = (String) b.get("measuredTime");
            return timeA.compareTo(timeB);
        });

        return result;
    }

    /**
     * 按天分组计算平均值（用于周、月等查询）
     * @param originalList 原始数据列表
     * @return 按天平均后的数据列表
     */
    private List<Map<String, Object>> processDailyAverage(List<Map<String, Object>> originalList) {
        if (ObjectUtil.isEmpty(originalList)) {
            return originalList;
        }

        // 使用Map来存储每天的数据，key为日期，value为该天的所有血糖值
        Map<String, List<Double>> dailyData = new HashMap<>();
        Map<String, String> dailyColor = new HashMap<>();

        for (Map<String, Object> item : originalList) {
            String measuredTime = item.get("measuredTime").toString();
            String bloodGlucoseStr = item.get("bloodGlucose").toString();
            String color = item.get("color") != null ? item.get("color").toString() : "green";

            try {
                // 解析日期时间，提取日期
                DateTime dateTime = DateUtil.parse(measuredTime);
                String dateKey = DateUtil.format(dateTime, "yyyy-MM-dd");

                double bloodGlucose = Double.parseDouble(bloodGlucoseStr);

                // 按天分组
                dailyData.computeIfAbsent(dateKey, k -> new ArrayList<>()).add(bloodGlucose);
                dailyColor.put(dateKey, color); // 保存颜色信息

            } catch (Exception e) {
                // 如果解析失败，跳过这条数据
                continue;
            }
        }

        // 计算每天的平均值
        List<Map<String, Object>> result = new ArrayList<>();
        for (Map.Entry<String, List<Double>> entry : dailyData.entrySet()) {
            String dateKey = entry.getKey();
            List<Double> values = entry.getValue();

            // 计算平均值
            double average = values.stream().mapToDouble(Double::doubleValue).average().orElse(0.0);

            Map<String, Object> resultItem = new HashMap<>();
            resultItem.put("measuredTime", dateKey);
            resultItem.put("bloodGlucose", String.format("%.1f", average));
            resultItem.put("color", dailyColor.get(dateKey));

            result.add(resultItem);
        }

        // 按时间排序
        result.sort((a, b) -> {
            String timeA = a.get("measuredTime").toString();
            String timeB = b.get("measuredTime").toString();
            return timeA.compareTo(timeB);
        });

        return result;
    }

}
